package com.hjq.mallware.service.impl;

import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjq.common.utils.PageUtils;
import com.hjq.common.utils.Query;

import com.hjq.mallware.dao.WareSkuDao;
import com.hjq.mallware.entity.WareSkuEntity;
import com.hjq.mallware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isNullOrEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");

        if(!StringUtils.isNullOrEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> wareSkuEntities = this.list(new QueryWrapper<WareSkuEntity>().eq("ware_id", wareId).eq("sku_id", skuId));
        if(wareSkuEntities==null||wareSkuEntities.size()==0){
            WareSkuEntity newSkuEntity = new WareSkuEntity();
            newSkuEntity.setSkuId(skuId);
            newSkuEntity.setStock(skuNum);
            newSkuEntity.setWareId(wareId);
            baseMapper.insert(newSkuEntity);
        }
        else {
            baseMapper.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public Boolean hasStock(Long skuId) {
        return getStockAmount(skuId)>0;
    }
    @Override
    public Integer getStockAmount(Long skuId) {
        List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId));
        if(wareSkuEntities.size()==0){
            return  0;
        }
        Integer count=0;
        for (WareSkuEntity wareSkuEntity:wareSkuEntities) {
            count+=wareSkuEntity.getStock()- wareSkuEntity.getStockLocked();

        }
            return count;
    }

}